package cn.zwk.drawing.domain.execution.model;

import lombok.Data;
import lombok.Builder;
import java.time.LocalDateTime;
import java.util.Map;

/**
 * 脚本执行结果
 */
@Data
@Builder
public class ExecutionResult {
    
    /**
     * 执行ID
     */
    private String executionId;
    
    /**
     * 节点ID
     */
    private String nodeId;
    
    /**
     * 能力ID
     */
    private String capabilityId;
    
    /**
     * 执行状态
     */
    private ExecutionStatus status;
    
    /**
     * 执行输出
     */
    private String output;
    
    /**
     * 错误信息
     */
    private String errorMessage;
    
    /**
     * 执行耗时（毫秒）
     */
    private Long duration;
    
    /**
     * 开始时间
     */
    private LocalDateTime startedAt;
    
    /**
     * 完成时间
     */
    private LocalDateTime completedAt;
    
    /**
     * 退出码
     */
    private Integer exitCode;
    
    /**
     * 额外的结果数据
     */
    private Map<String, Object> metadata;
    
    /**
     * 执行状态枚举
     */
    public enum ExecutionStatus {
        PENDING("pending", "等待中"),
        RUNNING("running", "执行中"),
        SUCCESS("success", "成功"),
        FAILED("failed", "失败"),
        TIMEOUT("timeout", "超时"),
        CANCELLED("cancelled", "已取消");
        
        private final String code;
        private final String description;
        
        ExecutionStatus(String code, String description) {
            this.code = code;
            this.description = description;
        }
        
        public String getCode() { return code; }
        public String getDescription() { return description; }
    }
    
    /**
     * 检查执行是否成功
     */
    public boolean isSuccess() {
        return ExecutionStatus.SUCCESS.equals(status);
    }
    
    /**
     * 检查执行是否完成
     */
    public boolean isCompleted() {
        return status == ExecutionStatus.SUCCESS || 
               status == ExecutionStatus.FAILED ||
               status == ExecutionStatus.TIMEOUT ||
               status == ExecutionStatus.CANCELLED;
    }
    
    /**
     * 获取格式化的输出
     */
    public String getFormattedOutput() {
        if (output == null) return "";
        
        StringBuilder sb = new StringBuilder();
        sb.append("=== ").append(capabilityId).append(" 执行结果 ===\n");
        sb.append("节点: ").append(nodeId).append("\n");
        sb.append("状态: ").append(status.getDescription()).append("\n");
        sb.append("耗时: ").append(duration).append("ms\n");
        sb.append("时间: ").append(completedAt).append("\n\n");
        sb.append(output);
        
        if (errorMessage != null) {
            sb.append("\n\n错误信息: ").append(errorMessage);
        }
        
        return sb.toString();
    }
}